#!/bin/bash

# Neural-SLAM 完整实验流程
# 用法: bash run_experiments.sh

set -e  # 遇到错误时停止

echo "🧪 Neural-SLAM 完整实验流程"
echo "=========================="

# 创建必要的目录
mkdir -p ./tmp/models/
mkdir -p ./results/

# 检查环境
echo "🔍 检查环境..."
python -c "import torch; print(f'PyTorch: {torch.__version__}')"
python -c "import ai2thor; print('AI2-THOR: OK')" || echo "⚠️ AI2-THOR 未安装"
python -c "import gymnasium; print('Gymnasium: OK')" || echo "⚠️ Gymnasium 未安装"

echo "=========================="
echo "开始实验流程..."
echo "=========================="

# 步骤1: 训练基线模型 (原始Neural-SLAM)
echo "📈 步骤1: 训练基线模型..."
python main.py \
    --exp_name baseline_original \
    --num_episodes 50 \
    --train_slam 1 \
    --train_global 1 \
    --train_local 1 \
    --max_episode_length 500 \
    --save_interval 10

echo "✅ 基线模型训练完成"

# 步骤2: 评估基线模型
echo "📊 步骤2: 评估基线模型..."
python main.py \
    --exp_name baseline_eval \
    --num_episodes 20 \
    --eval 1 \
    --load_slam "./tmp/models/baseline_original/" \
    --load_global "./tmp/models/baseline_original/" \
    --load_local "./tmp/models/baseline_original/" \
    --max_episode_length 500

echo "✅ 基线模型评估完成"

# 步骤3: 提取基线指标
echo "📋 步骤3: 提取基线指标..."
python extract_baseline_metrics.py \
    --log_dir "./tmp/" \
    --experiment "baseline" \
    --output_file "./results/baseline_metrics.json"

echo "✅ 基线指标提取完成"

# 步骤4: 训练改进模型
echo "🚀 步骤4: 训练改进模型..."
python main.py \
    --exp_name improved_model \
    --num_episodes 100 \
    --train_slam 1 \
    --train_global 1 \
    --train_local 1 \
    --max_episode_length 500 \
    --save_interval 10

echo "✅ 改进模型训练完成"

# 步骤5: 评估改进模型
echo "📊 步骤5: 评估改进模型..."
python main.py \
    --exp_name improved_eval \
    --num_episodes 20 \
    --eval 1 \
    --load_slam "./tmp/models/improved_model/" \
    --load_global "./tmp/models/improved_model/" \
    --load_local "./tmp/models/improved_model/" \
    --max_episode_length 500

echo "✅ 改进模型评估完成"

# 步骤6: 提取改进模型指标
echo "📋 步骤6: 提取改进模型指标..."
python extract_baseline_metrics.py \
    --log_dir "./tmp/" \
    --experiment "improved" \
    --output_file "./results/improved_metrics.json"

echo "✅ 改进模型指标提取完成"

# 步骤7: 生成对比报告
echo "📈 步骤7: 生成对比报告..."
python generate_paper_results.py \
    --baseline_dir "./tmp/" \
    --improved_dir "./tmp/" \
    --output_dir "./results/"

echo "✅ 对比报告生成完成"

# 步骤8: 显示结果总结
echo "=========================="
echo "🎉 实验流程完成！"
echo "=========================="
echo "📁 结果文件:"
echo "   - 模型权重: ./tmp/models/"
echo "   - 性能指标: ./results/"
echo "   - 训练日志: ./tmp/"
echo ""
echo "📊 关键文件:"
echo "   - ./results/baseline_metrics.json    # 基线性能"
echo "   - ./results/improved_metrics.json    # 改进模型性能"
echo "   - ./results/performance_comparison.png # 性能对比图"
echo "   - ./results/metrics_table.tex        # LaTeX表格"
echo ""
echo "🔍 查看结果:"
echo "   ls -la ./results/"
echo "   cat ./results/baseline_metrics.json"
echo "   cat ./results/improved_metrics.json"
